const express = require("express");
const app = express();
const port = 3000;
const jwt = require("express-jwt");

//解密token，获取token中的用户id
app.use(
  jwt({
    secret: "coderlee", //创建token时用的那个参数
    algorithms: ["HS256"], //加密算法
  }).unless({
    path: ["/api/open/login", "/api/open/reguser", "/api/open/article/list"], //除了这两个接口 其他接口都需要认证
  })
);

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.use("/api/open", require("./routers/login"));

app.use("/api/open", require("./routers/user"));

app.use("/api/open/upload", require("./routers/file"));

app.use("/api/open/article", require("./routers/article"));

app.use("/api/secure/upload", require("./routers/article-file"));

//错误处理中间件
app.use((err, req, res, next) => {
  if (err.name === "UnauthorizedError") {
    res.status(401).send({ status: 1, message: "login.unauthorized" });
  }
});

app.listen(port, () => {
  console.log(port + "启动了");
});
